package com.qmyx.supply.admin.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.google.common.collect.Lists;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.qmyx.supply.admin.model.response.FileResponse;
import com.qmyx.supply.admin.utils.AliyunOSSClientUtil;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.constants.BankerConstants;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.enums.KuaiDi100Enum;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.BankerImportErrorVO;
import com.ytjj.qmyx.supplychain.common.model.dto.ImportErrorDto;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.FileUploadRecordResponse;
import com.ytjj.qmyx.supplychain.common.model.response.ImportExcelFailResponse;
import com.ytjj.qmyx.supplychain.common.model.response.NewBankerOrderResponse;
import com.ytjj.qmyx.supplychain.common.utils.ExpressDicUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import com.ytjj.qmyx.supplychain.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description 订单
 * @ClassName OrderController
 *
 * 
 * @Version 1.0
 **/
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private BankerService bankerService;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private ExpressDicMapper expressDicMapper;
    @Resource
    private BankerImportErrorMapper bankerImportErrorMapper;
    @Resource
    private ExpressOrdersMapper expressOrdersMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private UploadRecordService uploadRecordServicer;
    @Autowired
    private BankerExportRecordService bankerExportRecordService;
    @Autowired
    private BankerOrderService bankerOrderService;
    @Autowired
    private ExpressDicService expressDicService;
    @Autowired
    private OrderExceptionService orderExceptionService;
    @Resource
    private OrderExceptionNoteMapper orderExceptionNoteMapper;
    /**
     * 批量插入订单快递单号
     *
     * @param file
     * @return
     */
    @PostMapping("/batchInsertOrders")
    public CommonResult batchInsertOrders(MultipartFile file) throws IOException {

        // 上传到oss
//        this.getImgUrl(file);

        // 导入订单
        Sheet sheet = new Sheet(1, 1, OrdersRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            log.info("表格数据：{}", JSONObject.toJSONString(list));
            orderService.batchInsertOrders(list.stream()
                    .map(item -> (OrdersRequest) item)
                    .collect(Collectors.toList()));
            return CommonResult.success(ResultCode.SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("导入发生异常：{}", e.getMessage());
        }
        return CommonResult.failed(ResultCode.FAILED);
    }

    /**
     * @Description 批量导出商家订单表列表
     *
     * 
     */
    @PostMapping("/batchExportOrders")
    public CommonResult batchExportOrders(@RequestBody ExportOrdersRequest exportOrdersRequest) {
        YxBanker userInfo = bankerService.getUserInfo();
        if (!userInfo.getLevel().equals(BankerConstants.LEVEL_PLATFORM)) {
            exportOrdersRequest.setBankerId(userInfo.getId());
        }
        return CommonResult.success(orderService.batchExportOrders(exportOrdersRequest));
    }


    /**
     * @Description 获取商家订单表列表
     *
     * 
     */
    @PostMapping("/getBankerOrderList")
    public CommonResult getBankerOrderList(@RequestBody OrderRequest request) {
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        request.setLevel(userInfo.getLevel());
        return CommonResult.success(orderService.getBankerOrderList(request));
    }

    /**
     * 添加商家订单表物流备注
     */
    @PostMapping("/addDeliveryRemark")
    public CommonResult addDeliveryRemark(@RequestBody DeliverRemarkAddRequest request) {
        orderService.addDeliveryRemark(request);
        return CommonResult.success();
    }

    /**
     * 平台获取订单列表 -> 用于导出
     * @return
     */
    @PostMapping("/getBankerOrders")
    public CommonResult getBankerOrders(@RequestBody PlatformExportRequest request) {
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        request.setLevel(userInfo.getLevel());
        return CommonResult.success(orderService.getBankerOrders(request));
    }


    /**
     * @Description 保存上传文件记录
     *
     * 
     * @Version 1.0
     **/

    @RequestMapping("/saveUploadFileRecord")
    public CommonResult saveUploadFileRecord(MultipartFile file) {
        FileResponse fileResponse = this.getImgUrl(file);
        // 获取当前的登录人的id
        Integer bankerId = bankerService.getUserInfo().getId();
        FileRequest fileRequest = new FileRequest()
                .setName(fileResponse.getName())
                .setUrl(fileResponse.getUrl())
                .setBankerId(bankerId);

        uploadRecordServicer.saveUploadFileRecord(fileRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * @Description 获取上传文件记录列表
     *
     * 
     */
    @PostMapping("/getUploadFileRecordList")
    public CommonResult getUploadFileRecordList(@RequestBody UploadRecordRequest uploadRecordRequest) {
        YxBanker userInfo = bankerService.getUserInfo();
        uploadRecordRequest.setBankerId(userInfo.getId());
        uploadRecordRequest.setLevel(userInfo.getLevel());
        CommonPage<FileUploadRecordResponse> commonPage = uploadRecordServicer.getUploadFileRecordList(uploadRecordRequest);
        List<FileUploadRecordResponse> fileUploadRecordResponseList = commonPage.getList();
        commonPage.setList(fileUploadRecordResponseList.stream().map(item -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            item.setUploadTimeText(simpleDateFormat.format(item.getUploadTime()));
            item.setBankerName(bankerMapper.selectByPrimaryKey(item.getBankerId()).getName());
            return item;
        }).collect(Collectors.toList()));
        return CommonResult.success(commonPage);

    }

    /**
     * @Description 更该文件是否下载状态
     *
     * 
     * @Version 1.0
     **/
    @PostMapping("/changeUploadFileDownloadStatus")
    public CommonResult changeUploadFileDownloadStatus(@RequestBody UploadFileStatusRequest uploadFileStatusRequest) {
        uploadRecordServicer.changeUploadFileDownloadStatus(uploadFileStatusRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 导出订单记录
     */
    @PostMapping("/getBankerExportRecordList")
    public CommonResult getBankerExportRecordList(@RequestBody QueryOrderRecordRequest queryOrderRecordRequest) {
        YxBanker userInfo = bankerService.getUserInfo();
        if (!userInfo.getLevel().equals(BankerConstants.LEVEL_PLATFORM)) {
            queryOrderRecordRequest.setBankerId(userInfo.getId());
        }
        queryOrderRecordRequest.setExportType(1);
        CommonPage commonPage = bankerExportRecordService.getBankerExportRecordList(queryOrderRecordRequest);
        return CommonResult.success(commonPage);
    }

    /**
     * @Description  检查是否导入过订单
     **/
    @PostMapping("/checkOrdersExpressInfo")
    public CommonResult checkOrdersExpressInfo(MultipartFile file) {
        Map<String,Object> returnMap = new HashMap<>();
        Sheet sheet = new Sheet(1, 1, OrdersExpressRequest.class);
        List<Object> list = null;
        try {
            list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("读到记录条数：{}", list.size());
        if (list.size() == 0){
            throw new ApiException("请导入正确的格式");
        }
        List<String> errorList = new ArrayList<>();
        List<String> orderNoList = new ArrayList<>();
        list.stream().filter(s -> !StringUtils.isEmpty(((OrdersExpressRequest)s).getExpressNo())).forEach(item ->{
            orderNoList.add(((OrdersExpressRequest) item).getChildOrderNo());
            try {
                String errorMsg = KuaiDi100Enum.getErrorMsg(((OrdersExpressRequest) item).getChildOrderNo(),((OrdersExpressRequest) item).getExpressCode(), ((OrdersExpressRequest) item).getExpressNo());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(errorMsg)) {
                    errorList.add(errorMsg);
                }

            } catch (Exception e) {
                log.error("校验快递单号失败！！:{}",e.getMessage());
            }
        });
        boolean flag = false;
        if (!CollectionUtils.isEmpty(orderNoList)){
            int count = bankerOrderService.checkOrdersExpressInfo(orderNoList);
            if (count > 0){
                String errorMsg ="您已导入快递，重复导入会覆盖之前的快递，是否继续";
                errorList.add(errorMsg);
            }
        }
        if (!CollectionUtils.isEmpty(errorList)) {
            flag = true;
        }
        returnMap.put("flag",flag);
        returnMap.put("msg",errorList);
        return CommonResult.success(returnMap);
    }


    @PostMapping("/checkExpressCodeAndNo")
    public CommonResult<String> checkExpressCodeAndNo(@RequestBody CheckExpressCodeRequest codeRequest) throws Exception{
        String errorMsg;
        if (codeRequest.getRequestType().equals(1)) {
            errorMsg = KuaiDi100Enum.getErrorMsg(codeRequest.getChildOrderNo(),ExpressDicUtil.getValue(codeRequest.getExpressCode().trim()), codeRequest.getExpressNo());
        } else {
            errorMsg = KuaiDi100Enum.getErrorMsg(codeRequest.getChildOrderNo(),codeRequest.getExpressCode(), codeRequest.getExpressNo());
        }

        return CommonResult.success(errorMsg);
    }

    /**
     * @Description 平台导入核对无误的表格 -> 更新快递信息
     * @Version 1.0
     **/
    @PostMapping("/updateOrdersExpressInfo")
    public CommonResult updateOrdersExpressInfo(MultipartFile file) {
        YxBanker userInfo = bankerService.getUserInfo();
        // 导入订单
        Sheet sheet = new Sheet(1, 1, OrdersExpressRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            log.info("读到记录条数：{}", list.size());
            List<YxBankerImportError> errorList = new ArrayList<>();
            List<String> returnGoodsList = new LinkedList<>();
            ImportErrorDto importErrorDto = new ImportErrorDto();
            list = list.stream().filter(s -> !StringUtils.isEmpty(((OrdersExpressRequest)s).getExpressNo())).collect(Collectors.toList());

            String redisExpressCompanyVal = redisService.get(RedisConstants.EXPRESS_COMPANY);
            if (StringUtils.isEmpty(redisExpressCompanyVal)) {
                List<YxExpressDic> yxExpressDicList = expressDicMapper.selectAll();
                Map<String, String> map = yxExpressDicList.stream()
                        .collect(Collectors.toMap(YxExpressDic::getExpressKey, YxExpressDic::getExpressValue));
                ExpressDicUtil.into(map);
                redisService.set(RedisConstants.EXPRESS_COMPANY, JSONObject.toJSONString(yxExpressDicList));
                redisService.expire(RedisConstants.EXPRESS_COMPANY, 60 * 60);
                yxExpressDicList = null;
                map = null;
            }else {
                List<YxExpressDic> yxExpressDicList = JSONObject.parseArray(redisExpressCompanyVal, YxExpressDic.class);
                Map<String, String> map = yxExpressDicList.stream()
                        .collect(Collectors.toMap(YxExpressDic::getExpressKey, YxExpressDic::getExpressValue));
                ExpressDicUtil.into(map);
                yxExpressDicList = null;
                map = null;
            }

            List<String> allReturnGoodsOrderNoList =  returnGoodsService.returningOrderList(userInfo.getId());
            List<String> allReturnGoodsOrderNoList2 =  orderService.queryReturnGoodsListIn30Day(userInfo.getLevel().equals(0) ? null : userInfo.getId());

            orderService.updateOrdersExpressInfo(list.stream()
                    .filter(item -> {
                        OrdersExpressRequest request = (OrdersExpressRequest) item;
                        boolean paramExceptionFlag = false;
                        boolean isContainExpressCompany = false;
                        // 参数非法(快递号）
                        if(Strings.isNotEmpty(request.getExpressNo())) {
                            String expressNo = request.getExpressNo().trim();
                            expressNo = expressNo.replaceAll("\\u00A0+|", "");
                            request.setExpressNo(expressNo);
                            paramExceptionFlag = isSpecialChar(request.getExpressNo());
                        }
                        // 参数为空
                        boolean emptyFlag = StringUtils.isEmpty(request.getExpressNo()) || StringUtils.isEmpty(request.getExpressCode()) || org.apache.commons.lang3.StringUtils.isBlank(request.getChildOrderNo());

                        // 快递公司是否存在
                        if(Strings.isNotEmpty(request.getExpressCode())) {
                            request.setExpressCode(request.getExpressCode().trim());
                            isContainExpressCompany = ExpressDicUtil.containKey(request.getExpressCode());
                        }
                        //校验订单是否退款
                        if ((!CollectionUtils.isEmpty(allReturnGoodsOrderNoList) && allReturnGoodsOrderNoList.contains(request.getChildOrderNo()))
                        || (!CollectionUtils.isEmpty(allReturnGoodsOrderNoList2) && allReturnGoodsOrderNoList2.contains(request.getChildOrderNo()))) {
                            returnGoodsList.add(request.getChildOrderNo());
                            return false;
                        }
                        log.info("发货导入快递单号参数为:{}",JSONObject.toJSONString(request));
                        if (emptyFlag || paramExceptionFlag || !isContainExpressCompany) {
                            YxBankerImportError yxBankerImportError = new YxBankerImportError();
                            yxBankerImportError.setBankerId(userInfo.getId());
                            yxBankerImportError.setBankerName(bankerMapper.selectByPrimaryKey((userInfo.getId())).getName());
                            yxBankerImportError.setCreateTime(new Date());
                            yxBankerImportError.setOrderNo(((OrdersExpressRequest) item).getChildOrderNo());
                            yxBankerImportError.setPlatformId(((OrdersExpressRequest) item).getId());
                            // 状态设置为显示
                            yxBankerImportError.setStatus((byte) 1);
                            if (org.apache.commons.lang3.StringUtils.isBlank(request.getChildOrderNo())) {
                                yxBankerImportError.setExceptionDes("订单ID为" + request.getOrderNo() + "的订单子订单号为空，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            // 已经导入过快递
                            List<YxBankerOrder> bankerOrderList = this.getBankerOrderList(request.getChildOrderNo());
                            if(bankerOrderList.size() > 0) {
                                yxBankerImportError.setExceptionDes("订单号为" + request.getChildOrderNo() + "的订单已导入过快递号，请不要重复导入！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(emptyFlag) {
                                yxBankerImportError.setExceptionDes("快递号为空的订单，快递单号或快递公司为空，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(paramExceptionFlag) {
                                yxBankerImportError.setExceptionDes("快递号为" + request.getExpressNo() + "的订单录入的快递号包含特殊字符，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(!isContainExpressCompany) {
                                yxBankerImportError.setExceptionDes("快递号为" + request.getExpressNo() + "的订单录入的快递公司名称不存在，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }

                        }
                        return true;
                    })
                    .map(item -> {
                        ((OrdersExpressRequest) item).getExpressNo().trim();
                        ((OrdersExpressRequest) item).getExpressCode().trim();
                        ((OrdersExpressRequest) item).setBankerId(userInfo.getId());
                        return (OrdersExpressRequest) item;
                    })
                    .collect(Collectors.toList()));
            importErrorDto.setErrorCount(errorList.size());
            importErrorDto.setSuccessCount(list.size() - errorList.size() - returnGoodsList.size());
            List<BankerImportErrorVO> importErrorVOList = new ArrayList<>();
            errorList.stream().forEach(item -> {
                BankerImportErrorVO vo = new BankerImportErrorVO();
                BeanUtils.copyProperties(item, vo);
                importErrorVOList.add(vo);
            });
            importErrorDto.setErrorList(importErrorVOList);
            importErrorDto.setReturnGoodsList(returnGoodsList);
            return CommonResult.success(importErrorDto);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("导入发生异常：{}", e.getMessage());
        }
        return CommonResult.failed(ResultCode.FAILED);
    }

    public static String dateToStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }

    @GetMapping("/getExpressList")
    public CommonResult getExpressList() {
        return CommonResult.success(expressDicService.getExpressList());
    }

    /**
     * @Description 修改单条订单记录
     * @Version 1.0
     **/
    @PostMapping("fillEmptyExpress")
    public CommonResult fillEmptyExpress(@RequestBody OrderExpressModifiedRequest orderExpressModifiedRequest) {
        if (!StringUtils.isEmpty(orderExpressModifiedRequest.getExpressNo())) {
            orderExpressModifiedRequest.setExpressNo(orderExpressModifiedRequest.getExpressNo().trim());
        }
        if (StringUtils.isEmpty(orderExpressModifiedRequest.getExpressNo())) {
            throw new ApiException("确认发货快递单号不能为空!");
        }

        bankerOrderService.fillEmptyExpress(orderExpressModifiedRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 刷新快递公司配置
     */
    @GetMapping("/refreshExpressDic")
    public CommonResult refreshExpressDic() {
        // 数据库读取配置文件
        List<YxExpressDic> yxExpressDicList = expressDicMapper.selectAll();
        Map<String, String> map = yxExpressDicList.stream()
                .collect(Collectors.toMap(YxExpressDic::getExpressKey, YxExpressDic::getExpressValue));
        ExpressDicUtil.into(map);
        return CommonResult.success(yxExpressDicList);
    }

    /**
     * @Description 处理异常订单
     * @Version 1.0
     **/
    @PostMapping("/updateExceptionHandleStatus")
    public CommonResult<List<ImportExcelFailResponse>> updateExceptionHandleStatus(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest) {
        YxBanker userInfo = bankerService.getUserInfo();
        if(StringUtils.isEmpty(exceptionOrdersRequest.getHandleNote())){
            throw new ApiException("处理备注不能为空！");
        }
        exceptionOrdersRequest.setStatus((byte) 2);
        exceptionOrdersRequest.setHandlePerson(userInfo.getId().toString());
        List<ImportExcelFailResponse> importExcelFailResponse = orderExceptionService.updateExceptionHandle(Arrays.asList(exceptionOrdersRequest));
        return CommonResult.success(importExcelFailResponse);
    }


    /**
     * 供应商异常订单跟踪页--新增备注
     * @return
     */
    @GetMapping("/batchInsertNote")
    public CommonResult batchInsertNote( String ids,String content) throws IOException {
        YxBanker userInfo = bankerService.getUserInfo();
        return orderExceptionService.insertNoteBatch(ids,content,userInfo.getId().toString());
    }

    @GetMapping("/updateOrderStatus")
    public CommonResult updateOrderStatus(@RequestParam("id") Integer id) {
        log.info("===供应商更新订单状态===2，{}", id);
        if(id == null) {
            throw new ApiException("ID不能为空！");
        }
        bankerOrderService.updateOrderStatus(id);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * @Description 上传文件
     * @Version 1.0
     **/
    public FileResponse getImgUrl(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ApiException("文件不存在");
        }
        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 ===>" + file.getOriginalFilename());
        FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file);
        if (fileResponse == null) {
            throw new ApiException("文件上传失败");
        }
        return fileResponse;
    }

    /**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        // String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        String regEx = "[ _.`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        // 快递单号长度小于6位为非法
        Boolean zeroExpressNoFlag = str.trim().length() < 6;
        return m.find() || zeroExpressNoFlag;
    }

    public List<YxBankerOrder> getBankerOrderList(String orderNo) {
        if (org.apache.commons.lang3.StringUtils.isBlank(orderNo)) {
            return new ArrayList<>();
        }
        Example example = new Example(YxBankerOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNo", orderNo);
        List<YxBankerOrder> bankerOrderList = bankerOrderMapper.selectByExample(example);
        bankerOrderList  = bankerOrderList.stream()
                .filter(item -> !StringUtils.isEmpty(item.getExpressNo()))
                .collect(Collectors.toList());
        return bankerOrderList;
    }

    /**
     * @Description 下载excel文件
     * @Version 1.0
     **/
    @GetMapping("/downloadExcel")
    public void download(Integer id, HttpServletResponse response) {
        YxBanker userInfo = bankerService.getUserInfo();
        bankerOrderService.downloadExcel(id, userInfo, response);
    }

    /* --------------------------------------------子订单------------------------------------------------ */

    /**
     * 子订单详情
     * @param orderNo
     * @return
     */
    @GetMapping("/findBankerOrderInfoByNo")
    public CommonResult findBankerOrderInfoByNo(@RequestParam(value = "childOrderNo", required = false) String childOrderNo,
                                                @RequestParam("orderNo") String orderNo) {
        return CommonResult.success(bankerOrderService.findBankerOrderInfoByNo(orderNo));
    }

    /**
     * 子订单 - 确认发货
     * newBankerOrderResponse
     * @return
     */
    @PostMapping("/confirmDelivery")
    public CommonResult confirmDelivery(@RequestBody NewBankerOrderResponse newBankerOrderResponse) {
        if (!StringUtils.isEmpty(newBankerOrderResponse.getExpressNo())) {
            newBankerOrderResponse.setExpressNo(newBankerOrderResponse.getExpressNo().trim());
        }
        if (StringUtils.isEmpty(newBankerOrderResponse.getExpressNo())) {
            throw new ApiException("确认发货快递单号不能为空!");
        }
        boolean confirmDelivery = bankerOrderService.confirmDelivery(newBankerOrderResponse);
        if (confirmDelivery) {
            return CommonResult.success(confirmDelivery);
        } else {
            return CommonResult.failed("售后订单不能发货");
        }

    }

    /**
     * 子订单 - 查看物流
     * @param tel
     * @param expressCode
     * @param expressNo
     * @return
     */
    @GetMapping("/getLogistics")
    public CommonResult getLogistics(@RequestParam String tel, @RequestParam String expressCode, @RequestParam String expressNo) {
        if (tel != null && expressCode != null && expressNo != null && !StringUtils.isEmpty(expressCode) && !StringUtils.isEmpty(expressNo)) {
            Example example = new Example(YxExpressOrders.class);
            example.createCriteria().andEqualTo("companyNo", expressCode).andEqualTo("expressEno", expressNo);
            example.orderBy("id").desc();
            List<YxExpressOrders> list = expressOrdersMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(list)) {
                return CommonResult.success(new ArrayList<>());
            }
            try {
                log.info("===getLogistics==={}", list.get(0).getInfoText());
                List<QueryTrackData> datas = JSONArray.parseArray(list.get(0).getInfoText(), QueryTrackData.class);
                return CommonResult.success(datas);
            } catch (Exception e) {
                return CommonResult.success(new ArrayList<>());
            }
        } else {
            return CommonResult.success(new ArrayList<>());
        }
    }


    @GetMapping("/pull")
    public void pullOrdersToBankerOrder(@RequestParam("orderNo") String orderNo) {
        log.info("=============> 开始从新系统拉取订单到供应商系统");
        orderService.pullOrderToJuishuitanSystem(orderNo);
        log.info("=============> 结束从新系统拉取订单到供应商系统");
    }

    @GetMapping("/updateFreight")
    public CommonResult updateFreight(@RequestParam(required = false) String startTime,@RequestParam(required = false) String endTime,@RequestParam(required = false) String childOrderNo){
        return orderService.updateFreight(startTime,endTime,childOrderNo);
    }

//    /**
//     * 批量供应商异常订单跟踪页--导入excel批量备注
//     * @return
//     */
//    @PostMapping("/batchInsertNote")
//    public CommonResult<List<ImportExcelFailResponse>> batchInsertNote(MultipartFile file) throws IOException {
//        YxBanker userInfo = bankerService.getUserInfo();
//        // 导入订单
//        Sheet sheet = new Sheet(1, 1, ImportBankerNoteRequest.class);
//        List<String> exceptionOrderClassify = ExceptionOrderClassifyEnum.getExceptionClassifyText();
//        try {
//            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
//            log.info("表格数据：{}", JSONObject.toJSONString(list));
//            List<ImportExcelFailResponse> notDealOrders = new ArrayList<>();
//            for(Object o:list) {
//                ImportBankerNoteRequest importBankerNoteRequest = (ImportBankerNoteRequest) o;
//                Integer id = importBankerNoteRequest.getId();
//                String remark = importBankerNoteRequest.getRemark();
////                String statusText = importBankerNoteRequest.getStatus();
//                String exceptionClassify = importBankerNoteRequest.getRemarkClassify();
//                if(StringUtils.isEmpty(remark) && StringUtils.isEmpty(exceptionClassify)){
//                    continue;
//                }
//                if(org.apache.commons.lang3.StringUtils.isNotBlank(exceptionClassify)){
//                    boolean isExistClassify = false;
//                    try {
//                        //截取序号
//                        String type = exceptionClassify.substring(0,exceptionClassify.indexOf(".")+1);
//                        isExistClassify = exceptionOrderClassify.contains(type);
//                    } catch (Exception e) {
//                        log.error("解析异常分类的序号出错：{}",e);
//                    }
//                    if(!isExistClassify){
//                        ImportExcelFailResponse failResponse = new ImportExcelFailResponse();
//                        failResponse.setId(id);
//                        failResponse.setMsg("异常分类不能为空！");
//                        notDealOrders.add(failResponse);
//                        continue;
//                    }
//                }
//                ExceptionOrdersRequest request = new ExceptionOrdersRequest();
//                request.setId(id);
//                //记录异常订单处理分类
//                if(org.apache.commons.lang3.StringUtils.isNotBlank(exceptionClassify)){
//                    Integer type = Integer.valueOf(exceptionClassify.substring(0, exceptionClassify.indexOf(".")));
//                    request.setExceptionClassify(type);
//                    String classifyName = ExceptionOrderClassifyEnum.getClassifyNameByType(Integer.valueOf(type));
//                    request.setExceptionOrderNote(classifyName);
//                }
////                if ("已处理".equals(statusText)){
////                    request.setStatus((byte) 2);
////                    request.setHandlePerson(userInfo.getId().toString());
////                }
//                //记录备注
//                request.setExceptionOrderNote(remark);
//                orderExceptionService.updateExceptionHandle(Lists.newArrayList(request));
//            }
//            return CommonResult.success(notDealOrders);
//        } catch (Exception e) {
//            log.info("导入发生异常：{}", e.getMessage());
//            String msg = e.getMessage();
//            msg = msg.substring(msg.lastIndexOf(":"));
//            return CommonResult.failed(msg);
//        }
//    }
}
